class SnakeGame {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.gridSize = 20;
        this.snake = [
            {x: 10, y: 10},
            {x: 9, y: 10},
            {x: 8, y: 10}
        ];
        this.direction = 'right';
        this.food = this.generateFood();
        this.score = 0;
        this.gameSpeed = 200;
        this.gameLoop = null;
        this.isPaused = false;
        this.isGameOver = false;

        // 初始化UI控制
        this.initControls();
    }

    initControls() {
        document.getElementById('startBtn').addEventListener('click', () => this.startGame());
        document.getElementById('pauseBtn').addEventListener('click', () => this.togglePause());
        document.getElementById('restartBtn').addEventListener('click', () => this.resetGame());
        
        const speedSlider = document.getElementById('speedSlider');
        speedSlider.addEventListener('input', () => {
            this.gameSpeed = 275 - (speedSlider.value * 20);
            document.getElementById('speedValue').textContent = speedSlider.value;
            if (this.gameLoop) {
                clearInterval(this.gameLoop);
                this.gameLoop = setInterval(() => this.update(), this.gameSpeed);
            }
        });

        // 键盘控制
        document.addEventListener('keydown', (e) => {
            if (this.isPaused || this.isGameOver) return;
            
            switch(e.key) {
                case 'ArrowUp': if (this.direction !== 'down') this.direction = 'up'; break;
                case 'ArrowDown': if (this.direction !== 'up') this.direction = 'down'; break;
                case 'ArrowLeft': if (this.direction !== 'right') this.direction = 'left'; break;
                case 'ArrowRight': if (this.direction !== 'left') this.direction = 'right'; break;
            }
        });
    }

    startGame() {
        if (this.gameLoop) clearInterval(this.gameLoop);
        this.isGameOver = false;
        this.gameLoop = setInterval(() => this.update(), this.gameSpeed);
    }

    togglePause() {
        this.isPaused = !this.isPaused;
        if (this.isPaused) {
            clearInterval(this.gameLoop);
        } else {
            this.gameLoop = setInterval(() => this.update(), this.gameSpeed);
        }
    }

    resetGame() {
        clearInterval(this.gameLoop);
        this.snake = [
            {x: 10, y: 10},
            {x: 9, y: 10},
            {x: 8, y: 10}
        ];
        this.direction = 'right';
        this.food = this.generateFood();
        this.score = 0;
        this.isGameOver = false;
        this.isPaused = false;
        document.getElementById('score').textContent = '0';
        this.draw();
    }

    generateFood() {
        let food;
        do {
            food = {
                x: Math.floor(Math.random() * (this.canvas.width / this.gridSize)),
                y: Math.floor(Math.random() * (this.canvas.height / this.gridSize))
            };
        } while (this.snake.some(segment => segment.x === food.x && segment.y === food.y));
        
        return food;
    }

    update() {
        if (this.isPaused || this.isGameOver) return;
        
        // 移动蛇
        const head = {...this.snake[0]};
        switch(this.direction) {
            case 'up': head.y--; break;
            case 'down': head.y++; break;
            case 'left': head.x--; break;
            case 'right': head.x++; break;
        }

        // 碰撞检测
        if (
            head.x < 0 || head.x >= this.canvas.width / this.gridSize ||
            head.y < 0 || head.y >= this.canvas.height / this.gridSize ||
            this.snake.some(segment => segment.x === head.x && segment.y === head.y)
        ) {
            this.gameOver();
            return;
        }

        this.snake.unshift(head);
        
        // 食物检测
        if (head.x === this.food.x && head.y === this.food.y) {
            this.score++;
            document.getElementById('score').textContent = this.score;
            this.food = this.generateFood();
            
            // 每100分加速5%
            if (this.score % 100 === 0) {
                this.gameSpeed = Math.max(75, this.gameSpeed * 0.95);
                clearInterval(this.gameLoop);
                this.gameLoop = setInterval(() => this.update(), this.gameSpeed);
            }
        } else {
            this.snake.pop();
        }
        
        this.draw();
    }

    gameOver() {
        this.isGameOver = true;
        clearInterval(this.gameLoop);
        alert(`游戏结束! 得分: ${this.score}`);
    }

    draw() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制蛇
        this.snake.forEach((segment, index) => {
            this.ctx.fillStyle = index === 0 ? '#4CAF50' : '#45a049';
            this.ctx.fillRect(
                segment.x * this.gridSize,
                segment.y * this.gridSize,
                this.gridSize,
                this.gridSize
            );
            
            // 蛇头眼睛
            if (index === 0) {
                this.ctx.fillStyle = 'white';
                const eyeSize = this.gridSize / 5;
                const eyeOffset = this.gridSize / 4;
                
                // 根据方向绘制眼睛
                if (this.direction === 'right' || this.direction === 'left') {
                    this.ctx.fillRect(
                        segment.x * this.gridSize + (this.direction === 'right' ? this.gridSize - eyeOffset : eyeOffset),
                        segment.y * this.gridSize + eyeOffset,
                        eyeSize, eyeSize
                    );
                    this.ctx.fillRect(
                        segment.x * this.gridSize + (this.direction === 'right' ? this.gridSize - eyeOffset : eyeOffset),
                        segment.y * this.gridSize + this.gridSize - eyeOffset * 1.5,
                        eyeSize, eyeSize
                    );
                } else {
                    this.ctx.fillRect(
                        segment.x * this.gridSize + eyeOffset,
                        segment.y * this.gridSize + (this.direction === 'down' ? this.gridSize - eyeOffset : eyeOffset),
                        eyeSize, eyeSize
                    );
                    this.ctx.fillRect(
                        segment.x * this.gridSize + this.gridSize - eyeOffset * 1.5,
                        segment.y * this.gridSize + (this.direction === 'down' ? this.gridSize - eyeOffset : eyeOffset),
                        eyeSize, eyeSize
                    );
                }
            }
        });
        
        // 绘制食物
        this.ctx.fillStyle = '#FF5252';
        this.ctx.beginPath();
        this.ctx.arc(
            this.food.x * this.gridSize + this.gridSize / 2,
            this.food.y * this.gridSize + this.gridSize / 2,
            this.gridSize / 2,
            0, Math.PI * 2
        );
        this.ctx.fill();
    }
}

// 启动游戏
const game = new SnakeGame();
game.draw();